<?php

/**
 * @file semaphore.php
 * @brief Clase para generar un semaforo
 * @author DyrTechnologies
 * @version V 1.0
 * @date Wed Oct 03 2007
 *
 *  Part of the CEFIRO dynamic web framework project
 *
 *  Copyright (C) 2007  Dyr technologies http://dyrtech.com.ve
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @class Clase semaphore
 */


/**
 * @brief Define la ruta a la hoja de estilos para el semaforo
 *
 */

require_once(CEF_IMAGE);
require_once(CEF_HIDDEN);
if(defined("LOG")){	
	require_once(LOG."fecha/Fecha.php");
	define("SERVER_DATES",1);
}
else
	define("SERVER_DATES",0);

define("SEM_IMG_SRC",FULL_URL."semaphore/img/");
define("RED_LIGHT","red.png");
define("YELLOW_LIGHT","yellow.png");
define("GREEN_LIGHT","green.png");

$semaphore_instance = 0;

class semaphore{

    private $low_percent;
    private $mid_percent;
    private $high_percent;
    private $curr_percent;
    private $reserv;
    private $reserv_percent;
    private $name;
    private $seminput;

    /**
     * Constructor de la clase semaforo
     *
     * @param integer $low
     * @param integer $mid
     * @param integer $high
     * @param string $_name
     * @return semaphore
     */

    public function semaphore($_name='__semaphore', $low=25, $mid=60, $high=100, $reserv = 0, $_seminput = false){
        /**
         * @brief Se asignan los valores a los atributos de la clase semaforo segun vengan dados al llamar al constructor de la misma notar que existen valores por omision para cada atributo
         */
        $this->low_percent=$low;
        $this->mid_percent=$mid;
        $this->high_percent=$high;
        $this->reserv = $reserv;
        if($_seminput)
       		$this->seminput = $_seminput;
       	else 
       		$this->seminput = false;

        /**
         * @brief $semaphore_instance es una variable para incrementar el numero de semaforos existentes
         */
        global $semaphore_instance;
        $semaphore_instance++;
        /**
         * @brief El nombre del widget es el tipo con el numero de la instancia que representa o el nombre pasado por omision en caso contrario
         */

        if($_name!="__semaphore")
        $this->name=$_name;
        else
        $this->name="semaphore".$semaphore_instance;


    }
    /**
     * @brief Ajusta los valores de un semaforo con dos condiciones
     *
     * @param string $prev_event
     * @param string $next_event
     * @param integer $current_quant
     * @param integer $desired_quant
     * @return semaphore La instancia de la clase
     */
    public function calc_dual_semaphore($prev_event, $next_event, $current_quant, $desired_quant, $delim='/'){

        /**
         * @brief Se obtiene la fecha actual para conseguir la distancia al próximo evento
         */
        if(SERVER_DATES)
        	$curr_date=Fecha::hoy(1);
        else{
            $curr_date=getdate();
            $curr_date=$curr_date['mday'].$delim.$curr_date['mon'].$delim.$curr_date['year'];
        }

        $diff = dateDiff($prev_event,$next_event,$delim);
        
        if ($diff > 0)
            $date_percent = dateDiff($prev_event,$curr_date,$delim)/$diff*100;
        else
            $date_percent = 100;

        /**
         * @brief Se obtiene las cantidades restantes para conseguir el porcentaje faltante
         */

      if(strlen($this->get_reserv()) > 0){
        //$current_quant += $this->get_reserv();
        if($desired_quant != 0)
        	$reserv_percent = ($desired_quant-$this->get_reserv())/$desired_quant*100;
        else 
        	$reserv_percent = 100;
      }
      $diff = $desired_quant-$current_quant;
      if($diff > 0 && $desired_quant != 0)
      	$quant_percent=$diff/$desired_quant*100;
      else 
      	$quant_percent=0;

        //$this->curr_percent=$date_percent>$quant_percent?$date_percent:$quant_percent;
    
        if($date_percent>$quant_percent)
            $this->curr_percent=$date_percent;
        else{
            $this->curr_percent=$quant_percent;
            $this->reserv_percent=$reserv_percent;
        }

    }

    /**
     * @brief Ajusta los valores de un semaforo con una sola condición
     *
     * @param string $a Cantidad Actual/Fecha del Evento Anterior
     * @param string $b Cantidad Deseada/Fecha del Próximo Evento
     * @return semaphore La instancia de la clase
     */
    public function calc_single_semaphore($a, $b, $delim='/'){
    	eco($a." ".$b);
        /**
         * @brief Si $a o $b no son números entonces se asume son fechas y los porcentajes son medidos en funcion del tiempo
         */
        if(!is_numeric($a)){
        /**
         * @brief Se obtiene la fecha actual para conseguir la distancia al próximo evento
         */
        
        if(SERVER_DATES)
            $curr_date=Fecha::hoy(1);
        else{
            $curr_date=getdate();
            $curr_date=$curr_date['mday'].$delim.$curr_date['mon'].$delim.$curr_date['year'];
        }
        
        $diff = dateDiff($a,$b,$delim);
        
        if ($diff > 0)
            $this->curr_percent = dateDiff($a,$curr_date,$delim)/$diff*100;
        else
            $this->curr_percent = 100;    
            
            //$this->curr_percent=dateDiff($a,$curr_date,$delim)/dateDiff($a,$b,$delim)*100;
        }

        /**
         * @brief Si $a y $b son números asumimos hablamos de cantidades y los porcentajes serán tomados como tales
         */
        else{
        /**
         * @brief Se obtiene las cantidades restantes para conseguir el porcentaje faltante
         */
          if(strlen($this->get_reserv()) > 0){
//            $a += $this->get_reserv();
            if($b>0)  
            	$this->reserv_percent = ($b-$this->get_reserv())/$b*100;
            else 
            	$this->reserv_percent = 100;
          }
          $diff = $b-$a;
          
          if($diff > 0 && $b != 0)
          	$this->curr_percent=$diff/$b*100;
          else
          	$this->curr_percent=0;
          	        
          	
        }
    }

    /**
     * @brief Las funciones get_VAR devuelven las variables que tenga ajustadas la instancia Niveles Porcentuales ($low_percent, $mid_percent, $high_percent), Nombre ($name), Porcentaje Actual ($curr_percent)
     *
     * @return string Valor de VAR
     */
    public function get_low(){
        return $this->low_percent;
    }

    public function get_mid(){
        return $this->mid_percent;
    }

    public function get_high(){
        return $this->high_percent;
    }

    public function get_curr(){
        return $this->curr_percent;
    }

    public function get_name(){
        return $this->name;
    }

    public function get_reserv(){
      return $this->reserv;
    }
    
    public function get_seminput(){
    	return $this->seminput;
    }

    public function get_curr_reserv(){
      return $this->reserv_percent;
    }

    /**
     * @brief Las funciones set_VAR ajustan las variables de la instancia Niveles Porcentuales ($low_percent, $mid_percent, $high_percent), Nombre ($name), Porcentaje Actual ($curr_percent)
     */

    public function set_low($_low){
        $this->low_percent=$_low;
    }

    public function set_mid($_mid){
        $this->mid_percent=$_mid;
    }

    public function set_high($_high){
        $this->high_percent=$_high;
    }

    public function set_reserv($_reserv){
      $this->reserv = $_reserv;
    }

    public function set_name($_name){
        $this->name=$_name;
    }
    
    public function set_seminput($_seminput = false){
    	if($_seminput)
    		$this->seminput = $_seminput;
    	else 
    		$this->seminput = false;
    }

    /**
     * @brief Devuelve el semaforo como una cadena con sus parametros
     *
     * @return string $retval
     */
    public function get_semaphore(){
        $retval="";

        if( strlen( $this->get_name() ) > 0)
        $retval.=$this->get_name()." ";
        if( strlen( $this->get_low() ) > 0)
        $retval.=$this->get_low()." ";
        if( strlen( $this->get_mid() ) > 0)
        $retval.=$this->get_mid()." ";
        if( strlen( $this->get_high() ) > 0)
        $retval.=$this->get_high()." ";
        if( strlen( $this->get_curr() ) > 0)
        $retval.=$this->get_curr()." ";
        if( strlen( $this->get_reserv() ) > 0)
        $retval.=$this->get_reserv()." ";
        if( strlen( $this->get_curr_reserv() ) > 0)
        $retval.=$this->get_curr_reserv()." ";

        return $retval;
    }

    /**
     * @brief Devuelve el Color del Semaforo
     *
     * @return string color
     */
    public function get_color(){
        if($this->get_curr()<=$this->get_low())
        return GREEN_LIGHT;
        elseif ($this->get_curr()<=$this->get_mid())
        return YELLOW_LIGHT;
        else
        return RED_LIGHT;
    }

    /**
     * @brief Asigna el semaforo a la variable $smarty para su renderizacion
     *
     */
    public function display_semaphore($fetch = false){
        $color=$this->get_color();
        $semaphore_image = new imagece($this->get_name().$color,SEM_IMG_SRC.$color,$color);
        $semaphore_image->set_height("30px");
        $semaphore_image->set_width("30px");
        $semaphore_image = $semaphore_image->display_image(true);

        if($this->get_seminput()){
        	switch ($color) {
        		case RED_LIGHT:
        			$colorvalue = -1;
        			break;
        		case GREEN_LIGHT:
        			$colorvalue = 1;
        			break;
        		default:
        			$colorvalue = 0;
        			break;
        	}
        	$seminput = new hidden($this->name,$colorvalue); 
        }
        global $smarty;

        if(!$fetch){
        	if($this->get_seminput())
            	$smarty->assign( $this->name , $semaphore_image.$seminput->display_hidden(true) );
            else 
            	$smarty->assign( $this->name , $semaphore_image);
            return 1;
        }
        else{
        	if($this->get_seminput())
            	return $semaphore_image.$seminput->display_hidden(true);
            else 
            	return $semaphore_image;
        }
    }
}

?>